package com.spring.lesson.jdbc;

import com.spring.lesson.generic.UserServiceImpl;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class TestJdbcTemplate {

    private ApplicationContext context;
    private JdbcTemplate template;

    @Before
    public void init() {
        context = new ClassPathXmlApplicationContext("application-jdbc.xml");
        template = (JdbcTemplate) context.getBean("jdbcTemplate");
    }

    @Test
    public void testInsert() throws Exception {
        int row = template.update("insert into t_user values(null,?,?)", "咱三", "2018-10-21");
        System.out.println(row > 0 ? "成功":"失败");
    }
    
    @Test
    public void testQuery() {
        List<UserInfo> list = template.query("select * from t_user", new RowMapper<UserInfo>() {
            @Override
            public UserInfo mapRow(ResultSet resultSet, int i) throws SQLException {
                UserInfo user = new UserInfo();
                user.setUserId(resultSet.getInt("user_id"));
                user.setUserBirth(resultSet.getDate("user_birth"));
                user.setUserName(resultSet.getString("user_name"));

                return user;
            }
        });

        for (UserInfo user : list) {
            System.out.println(user.getUserId() + ","+ user.getUserName());
        }
    }
    
}
